package com.dl.mall.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * sentinel配置类
 * @author DL
 * @create 2022-05-12 14:47
 */
@Configuration
public class SentinelConfig {
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    @PostConstruct
    private void initRules() {
        //=============================规则1=========================
        FlowRule rule1 = new FlowRule();
        rule1.setResource("limiting");//规则名称
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);//如果设置0则按照线程数限流，如果设置1则按照QPS（每秒查询率）限流
        rule1.setCount(30);   // 每秒调用最大次数为 10 次
        rule1.setControlBehavior(1);// 0.默认值（直接拒绝）1.预警 2.降级 3.预警+降级
        rule1.setMaxQueueingTimeMs(1000);//排队超时阈值
        //=============================规则2=========================
        FlowRule rule2 = new FlowRule();
        rule2.setResource("seckill");//规则名称
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule2.setCount(1000);
        rule2.setControlBehavior(1);
        rule2.setMaxQueueingTimeMs(2000);

        List<FlowRule> rules = new ArrayList<>();
        rules.add(rule1);
        rules.add(rule2);
        // 将控制规则载入到 Sentinel
        FlowRuleManager.loadRules(rules); // 修改流控规则
    }
}

